package com.nova.android.tvlauncher.apkinstall

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInstaller
import android.os.Build
import kotlinx.coroutines.channels.Channel

data class InstallResult(val status: Int, val message: String?)

class InstallReceiver : BroadcastReceiver() {
    companion object {
        // 使用 Channel 传递安装结果
        var resultChannel = Channel<InstallResult>(1)
    }

    override fun onReceive(context: Context, intent: Intent) {
        val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, -1)
        val message = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE)
        //println("当前安装的信息是：$message-----$intent")
        when (status) {
            PackageInstaller.STATUS_PENDING_USER_ACTION -> {
                val userIntent = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
                    @Suppress("DEPRECATION")
                    intent.getParcelableExtra(Intent.EXTRA_INTENT)
                } else {
                    intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)
                }

                if (userIntent != null) {
                    userIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    context.startActivity(userIntent)
                } else {
                }
            }

            PackageInstaller.STATUS_SUCCESS -> {
                // 使用 trySend 发送结果（非阻塞）
                resultChannel.trySend(InstallResult(status, "安装成功"))
            }

            PackageInstaller.STATUS_FAILURE_ABORTED -> {
                // 使用 trySend 发送结果（非阻塞）
                resultChannel.trySend(InstallResult(status, "取消安装"))
            }

            else -> {
                // 使用 trySend 发送结果（非阻塞）
                resultChannel.trySend(InstallResult(status, "安装失败"))
            }

        }
    }
}